const Product = require('../models/Product')
const Response = require('../utils/response')
const { validationResult } = require('express-validator')

// 获取商品列表
exports.getProductList = async (req, res) => {
  try {
    const { page = 1, limit = 20, category, keyword } = req.query
    
    const result = await Product.getList(
      parseInt(page),
      parseInt(limit),
      category,
      keyword
    )

    return Response.success(res, result)
  } catch (error) {
    console.error('获取商品列表错误:', error)
    return Response.error(res, '获取商品列表失败', 500)
  }
}

// 获取商品详情
exports.getProductDetail = async (req, res) => {
  try {
    const { id } = req.params
    const product = await Product.findById(id)

    if (!product) {
      return Response.notFound(res, '商品不存在')
    }

    return Response.success(res, product)
  } catch (error) {
    console.error('获取商品详情错误:', error)
    return Response.error(res, '获取商品详情失败', 500)
  }
}

// 创建商品（管理员功能）
exports.createProduct = async (req, res) => {
  try {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return Response.error(res, errors.array()[0].msg, 400)
    }

    const result = await Product.create(req.body)

    return Response.success(res, { id: result.insertId }, '商品创建成功')
  } catch (error) {
    console.error('创建商品错误:', error)
    return Response.error(res, '创建商品失败', 500)
  }
}

// 更新商品
exports.updateProduct = async (req, res) => {
  try {
    const { id } = req.params
    
    // 检查商品是否存在
    const product = await Product.findById(id)
    if (!product) {
      return Response.notFound(res, '商品不存在')
    }

    await Product.update(id, req.body)

    return Response.success(res, null, '商品更新成功')
  } catch (error) {
    console.error('更新商品错误:', error)
    return Response.error(res, error.message || '更新商品失败', 500)
  }
}

// 删除商品
exports.deleteProduct = async (req, res) => {
  try {
    const { id } = req.params
    
    // 检查商品是否存在
    const product = await Product.findById(id)
    if (!product) {
      return Response.notFound(res, '商品不存在')
    }

    await Product.delete(id)

    return Response.success(res, null, '商品删除成功')
  } catch (error) {
    console.error('删除商品错误:', error)
    return Response.error(res, '删除商品失败', 500)
  }
}

// 获取热销商品
exports.getHotProducts = async (req, res) => {
  try {
    const { limit = 10 } = req.query
    const products = await Product.getHotProducts(parseInt(limit))

    return Response.success(res, products)
  } catch (error) {
    console.error('获取热销商品错误:', error)
    return Response.error(res, '获取热销商品失败', 500)
  }
}

// 获取商品分类列表
exports.getCategories = async (req, res) => {
  try {
    const categories = await Product.getCategories()
    return Response.success(res, categories)
  } catch (error) {
    console.error('获取分类列表错误:', error)
    return Response.error(res, '获取分类列表失败', 500)
  }
}

// 上传商品图片
exports.uploadImage = async (req, res) => {
  try {
    if (!req.file) {
      return Response.error(res, '请选择要上传的图片', 400)
    }

    // 返回图片访问URL
    const imageUrl = `/uploads/products/${req.file.filename}`
    
    return Response.success(res, { 
      url: imageUrl,
      filename: req.file.filename,
      originalname: req.file.originalname,
      size: req.file.size
    }, '图片上传成功')
  } catch (error) {
    console.error('上传图片错误:', error)
    return Response.error(res, error.message || '图片上传失败', 500)
  }
}

// 删除商品图片
exports.deleteImage = async (req, res) => {
  try {
    const { filename } = req.params
    const fs = require('fs')
    const path = require('path')
    
    const filePath = path.join(__dirname, '../uploads/products', filename)
    
    // 检查文件是否存在
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath)
      return Response.success(res, null, '图片删除成功')
    } else {
      return Response.notFound(res, '图片不存在')
    }
  } catch (error) {
    console.error('删除图片错误:', error)
    return Response.error(res, '图片删除失败', 500)
  }
}

